<?php

namespace app\common\controller;
use app\common\exception\OptionsException;
use app\common\exception\ParameterException;
use app\common\exception\TokenException;
use app\common\exception\UserException;
use think\Controller;
use think\Exception;
use think\Validate;
use app\common\logic\User as UserLogic;


header("Access-Control-Allow-Origin:  *" );
header("Content-type: application/json");
header("Access-Control-Allow-Methods: GET, OPTIONS, POST, PUT");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding, X-Requested-With, Origin, Authorization");

class Base extends Controller {
    /*
     * 初始化操作
     */
    protected  $uid;
    protected  $type;
    protected  $new_token;
    public function __construct()
    {
        parent::__construct();
        $token = Token::decode();

        $uid = $token['data']['uid'];
        $this->uid=$uid;
        if (request()->isOptions()) throw new OptionsException();
        if($token['data']['new_token']){
            $this->new_token=$token['data']['new_token'];
        }

        $jwt = '';
        // header中有无token
        try {
            $type=request()->post('user_type');
            $this->type=$type;
            if(!$this->type){
                $ret = ["code"=>201, "msg"=>"参数错误","errorCode"=>300];
                throw new ParameterException($ret);
            }
            $rule = [
                'type'  => 'require|number',

            ];
            $msg = [
                'type.require' => '非法操作,未接受到状态参数',
                'type.number'     => '非法操作,状态参数不是数字',

            ];
            $data = [
                'type'  => $type,

            ];
            $validate = new Validate($rule,$msg);
            $result   = $validate->check($data);
            if(!$result){

                throw  new ParameterException(['code' => 201,"msg"=>$validate->getError()]);


            }
            $userlogic=new UserLogic();
            $res=$userlogic->get_users_byid($uid,$type);

            if ($res["code"]!=200) {
                throw new UserException($res);
            }

        } catch (Exception $e) {

            $ret = ["code"=>201, "msg"=>"登陆过期","errorCode"=>300];
            throw new UserException($ret);

        }
        if (!empty($jwt)) {
            response()->header(['token' => $jwt])->send();
        }
    }

}